package com.atguigu02.tcpudp;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ClassName: PictuerTranTest
 * Package: com.atguigu02.tcpudp
 * Description:
 *
 * @Author BuTang
 * @Create 2023/6/20 16:16
 * @Version 1.0
 */
public class PictuerTranTest {


    //客户端
    @Test
    public void test1() throws IOException {
        //1.创建socket
        int port = 8989;
        InetAddress inetAddress = InetAddress.getByName("192.168.10.55");
        Socket socket = new Socket(inetAddress,port);

        //2.创建输入和输出流
        OutputStream ou = socket.getOutputStream();
        File file = new File("dog.jpg");
        FileInputStream in = new FileInputStream(file);

        int len;
        byte[] buffer = new byte[5];
        while ((len = in.read(buffer)) != -1) {
            ou.write(buffer,0,len);
        }

        //3.关闭流
        socket.close();
        ou.close();
        in.close();
    }


    //服务器端
    @Test
    public void test2() throws IOException {

        //1.创建 服务器的socket以及客户端的socket
        int port = 8989;
        ServerSocket serverSocket = new ServerSocket(port);
        Socket socket =serverSocket.accept();

        //2.创建流 和目标
        File newpic = new File("dog_1.jpg");
        OutputStream ou = new FileOutputStream(newpic);
        InputStream in = socket.getInputStream();

        //3.进行数据的接收和写出
        int len ;
        byte[] buffer = new byte[5];
        ByteArrayOutputStream by = new ByteArrayOutputStream();
        while((len = in.read(buffer)) != -1) {
            ou.write(buffer);
        }

        //4.关闭流
        serverSocket.close();
        socket.close();
        ou.close();
        in.close();
    }
}
